package org.jinyan.servlet;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.jinyan.admin.model.MyUser;

/**
 * 单点登录 如果你在别的其他机器上已经登录，系统提示账号已经登录，不能登录
 * 
 * @author Administrator
 * 
 */
public class LoginSessionListener implements HttpSessionAttributeListener {

	Map<String, HttpSession> map = new HashMap<String, HttpSession>();

	// session属性添加的时候被调用
	public void attributeAdded(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		String name = event.getName();
		if (name == "person") {
			MyUser person = (MyUser) event.getValue();

			if (map.get(person.getUsername()) != null) {
				HttpSession session = map.get(person.getUsername());

				MyUser personOld = (MyUser) session.getAttribute("person");

				session.setAttribute("sms", "账号" + personOld.getUsername()
						+ "已经在ip为" + "机子上登录，你被迫下线");

				session.removeAttribute("person");
			}

			// 将session以用户名为索引放入session
			map.put(person.getUsername(), event.getSession());
		}
	}

	// session属性删除的时候调用
	public void attributeRemoved(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub

		String name = event.getName();
		if (name.equals("person")) {
			MyUser person = (MyUser) event.getValue();
			// 移除的session在map中移除
			map.remove(person.getUsername());
			System.out.println("账号" + person.getUsername() + "已经退出。");
		}
	}

	// session属性修改的时候调用
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub

		String name = event.getName();
		if (name.equals("person")) {
			MyUser oldPerson = (MyUser) event.getValue();
			// 移除旧的登录信息
			map.remove(oldPerson.getUsername());

			// 新的的登录信息
			MyUser person = (MyUser) event.getSession().getAttribute("person");

			// 判断是否在别的机器上登录过
			if (map.get(person.getUsername()) != null) {
				HttpSession session = map.get(person.getUsername());
				session.removeAttribute("person");
				session.setAttribute("sms", "你的账号在别的机器上登录，你被迫下线。");
			}
			map.put(person.getUsername(), event.getSession());
		}
	}

}